import request from '@/service/request'

//临时上传凭证
export function uploadFile(fileName, scene) {
  return request.get('/oss/upload/url', {
    params: {
      fileName,
      scene,
    },
  })
}

//真实上传
// export async function uploadFileByUrl(uploadUrl: string, fileType: string, file: File | Blob) {
//   return request.put(
//     uploadUrl,
//       file,

//     {
//       headers: {
//         'Content-Type': fileType,
//         Accept: '*/*',
//         Host: '10.104.0.106:9080',
//         Connection: 'keep-alive',
//       },
//     },
//   )
// }


export function uploadFileByUrl(uploadUrl: string, fileType: string, file: File | Blob): Promise<any> {
  return new Promise((resolve, reject) => {
    const xhr = new XMLHttpRequest()
    xhr.open('PUT', uploadUrl, true)
    xhr.setRequestHeader('Content-Type', fileType)


    xhr.onload = function () {
      if (xhr.status >= 200 && xhr.status < 300) {
        resolve(xhr.response)
      } else {
        reject(new Error(`Upload failed: ${xhr.status} ${xhr.statusText}`))
      }
    }
    xhr.onerror = function () {
      reject(new Error('Network error'))
    }
    xhr.send(file)
  })
}


// export async function uploadFileByUrl(uploadUrl: string, fileType: string, file: File | Blob) {
//   const myHeaders = new Headers()
//   myHeaders.append('Content-Type', fileType)
//   myHeaders.append('Accept', '*/*')
//   myHeaders.append('Host', '10.104.0.106:9080')
//   myHeaders.append('Connection', 'keep-alive')

//   const file1 = file

//   const requestOptions = {
//     method: 'PUT',
//     headers: myHeaders,
//     body: file1,
//     redirect: 'follow',
//   }

//   return fetch(
//     uploadUrl,
//     requestOptions,
//   )
//     .then((response) => response.text())
//     .then((result) => console.log(result))
//     .catch((error) => console.log('error', error))
// }
